package cn.codeforfun.common;

import cn.codeforfun.consts.SessionConsts;
import cn.codeforfun.follower.FollowerService;
import cn.codeforfun.interceptor.LoginInterceptor;
import cn.codeforfun.interceptor.OauthInterceptor;
import cn.codeforfun.user.User;
import cn.codeforfun.user.UserService;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Administrator on 2017/2/14 0014.
 */
@Controller
public class IndexController {
    @Autowired
    private UserService userService;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private FollowerService followerService;

    @RequestMapping("/")
    @LoginInterceptor
    public String index(Model model) {
        return "index.html";
    }

    @RequestMapping("/survey")
    @OauthInterceptor
    public String survey(Model model) throws WxErrorException, IOException {
        return "/survey.html";
    }

    @RequestMapping("/infoPage")
    @OauthInterceptor
    public String infoPage(Model model) {
        return "infoPage.html";
    }

    @RequestMapping("/result")
    @OauthInterceptor
    public String result(Model model) {
        return "result.html";
    }

    @RequestMapping("/loginPage")
    public String loginPage(Model model) {
        return "loginPage.html";
    }

    @RequestMapping("/logout")
    @ResponseBody
    public void logout(HttpSession session) {
        session.invalidate();
    }


    @RequestMapping("/baojie")
    @OauthInterceptor
    public String baojie(@RequestParam String id, String code, String state, Model model, HttpSession session) {
        session.setAttribute(SessionConsts.VOTE_ID, id);
        return "baojie.html";
    }

    @RequestMapping("/login")
    @ResponseBody
    public boolean login(@RequestBody User user, HttpSession session) {
        String username = user.getUsername();
        String password = user.getPassword();
        if (StringUtils.isEmpty(username.trim()) || StringUtils.isEmpty(password.trim())) return false;
        user = userService.checkUserByUsernameAndPassword(username.trim(), password.trim());
        if (user != null) {
            session.setAttribute(SessionConsts.USER, user);
            return true;
        } else
            return false;
    }
}
